<template>
  <div class="app-container">
    <t-form
      :data="queryParams"
      ref="queryRef"
      v-show="showSearch"
      layout="inline"
      label-width="68px"
      class="mb20"
    >
      <t-form-item label="角色名称" name="roleName">
        <t-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </t-form-item>
      <t-form-item label="权限字符" name="roleKey">
        <t-input
          v-model="queryParams.roleKey"
          placeholder="请输入权限字符"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </t-form-item>
      <t-form-item label="状态" name="status">
        <t-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          style="width: 240px"
        >
          <t-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </t-select>
      </t-form-item>
      <t-form-item label="创建时间" style="width: 308px">
        <t-date-range-picker v-model="dateRange" allow-input clearable />
      </t-form-item>
      <t-form-item>
        <t-space>
          <t-button theme="primary" @click="handleQuery">
            搜索
            <template #icon>
              <t-icon name="search" />
            </template>
          </t-button>
          <t-button theme="default" @click="resetQuery">
            重置
            <template #icon>
              <t-icon name="refresh" />
            </template>
          </t-button>
        </t-space>
      </t-form-item>
    </t-form>
    <t-row :gutter="10" class="mb8">
      <t-col :span="1.5">
        <t-button
          theme="primary"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
          >新增
          <template #icon>
            <t-icon name="add" />
          </template>
        </t-button>
      </t-col>
      <t-col :span="1.5">
        <t-button
          theme="success"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
          >修改
          <template #icon>
            <t-icon name="edit" />
          </template>
        </t-button>
      </t-col>
      <t-col :span="1.5">
        <t-button
          theme="danger"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
          >删除
          <template #icon>
            <t-icon name="delete" />
          </template>
        </t-button>
      </t-col>
      <t-col :span="1.5">
        <t-button
          theme="warning"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
          >导出
          <template #icon>
            <t-icon name="download" />
          </template>
        </t-button>
      </t-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </t-row>

    <!-- 表格数据 -->
    <t-table
      v-loading="loading"
      row-key="roleId"
      :columns="columns"
      :data="roleList"
      :selected-row-keys="ids"
      @select-change="handleSelectionChange"
    >
      <template #status="{ row }">
        <t-switch
          v-model="row.status"
          :customValue="['0', '1']"
          @change="handleStatusChange(row)"
        ></t-switch>
      </template>
      <template #createTime="{ row }">
        <span>{{ parseTime(row.createTime) }}</span>
      </template>
      <template #action="{ row }">
        <t-tooltip content="修改" placement="top" v-if="row.roleId !== 1">
          <t-button
            variant="text"
            theme="primary"
            @click="handleUpdate(row)"
            v-hasPermi="['system:role:edit']"
          >
            <template #icon>
              <t-icon name="edit" />
            </template>
          </t-button>
        </t-tooltip>
        <t-tooltip content="删除" placement="top" v-if="row.roleId !== 1">
          <t-button
            variant="text"
            theme="primary"
            @click="handleDelete(row)"
            v-hasPermi="['system:role:remove']"
          >
            <template #icon>
              <t-icon name="delete" />
            </template>
          </t-button>
        </t-tooltip>
        <t-tooltip content="数据权限" placement="top" v-if="row.roleId !== 1">
          <t-button
            variant="text"
            theme="primary"
            @click="handleDataScope(row)"
            v-hasPermi="['system:role:edit']"
          >
            <template #icon>
              <t-icon name="check-circle" />
            </template>
          </t-button>
        </t-tooltip>
        <t-tooltip content="分配用户" placement="top" v-if="row.roleId !== 1">
          <t-button
            variant="text"
            theme="primary"
            @click="handleAuthUser(row)"
            v-hasPermi="['system:role:edit']"
          >
            <template #icon>
              <t-icon name="user" />
            </template>
          </t-button>
        </t-tooltip>
      </template>
    </t-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <t-dialog :title="title" v-model:visible="open" width="500px" attach="body">
      <t-form ref="roleRef" :data="form" :rules="rules" label-width="100px">
        <t-form-item label="角色名称" name="roleName">
          <t-input v-model="form.roleName" placeholder="请输入角色名称" />
        </t-form-item>
        <t-form-item name="roleKey">
          <template #label>
            <span>
              <t-tooltip
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
                placement="top"
              >
                <t-icon name="help-circle-filled" />
              </t-tooltip>
              权限字符
            </span>
          </template>
          <t-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </t-form-item>
        <t-form-item label="角色顺序" name="roleSort">
          <t-input-number
            v-model="form.roleSort"
            controls-position="right"
            :min="0"
          />
        </t-form-item>
        <t-form-item label="状态">
          <t-radio-group v-model="form.status">
            <t-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></t-radio>
          </t-radio-group>
        </t-form-item>
        <t-space>
          <t-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
            >展开/折叠</t-checkbox
          >
          <t-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
            >全选/全不选</t-checkbox
          >
          <t-checkbox
            v-model="form.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')"
            >父子联动</t-checkbox
          >
        </t-space>
        <t-form-item label="菜单权限">
          <t-tree
            class="tree-border"
            :data="menuOptions"
            checkable
            v-model:expanded="menuExpandedKeys"
            ref="menuRef"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty="加载中，请稍候"
            :keys="{ value: 'id', label: 'label', children: 'children' }"
          ></t-tree>
        </t-form-item>
        <t-form-item label="备注">
          <t-textarea
            v-model="form.remark"
            placeholder="请输入内容"
          ></t-textarea>
        </t-form-item>
      </t-form>
      <template #footer>
        <div class="dialog-footer">
          <t-button theme="primary" @click="submitForm">确 定</t-button>
          <t-button theme="default" @click="cancel">取 消</t-button>
        </div>
      </template>
    </t-dialog>

    <!-- 分配角色数据权限对话框 -->
    <t-dialog
      :title="title"
      v-model:visible="openDataScope"
      width="500px"
      attach="body"
    >
      <t-form :data="form" label-width="80px">
        <t-form-item label="角色名称">
          <t-input v-model="form.roleName" :disabled="true" />
        </t-form-item>
        <t-form-item label="权限字符">
          <t-input v-model="form.roleKey" :disabled="true" />
        </t-form-item>
        <t-form-item label="权限范围">
          <t-select v-model="form.dataScope" @change="dataScopeSelectChange">
            <t-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></t-option>
          </t-select>
        </t-form-item>
        <t-space>
          <t-checkbox
            v-model="deptExpand"
            @change="handleCheckedTreeExpand($event, 'dept')"
            >展开/折叠</t-checkbox
          >
          <t-checkbox
            v-model="deptNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'dept')"
            >全选/全不选</t-checkbox
          >
          <t-checkbox
            v-model="form.deptCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'dept')"
            >父子联动</t-checkbox
          >
        </t-space>
        <t-form-item label="数据权限" v-show="form.dataScope == 2">
          <t-tree
            class="tree-border"
            :data="deptOptions"
            checkable
            default-expand-all
            v-model:expanded="deptExpandedKeys"
            ref="deptRef"
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            empty="加载中，请稍候"
            :keys="{ value: 'id', label: 'label', children: 'children' }"
          ></t-tree>
        </t-form-item>
      </t-form>
      <template #footer>
        <div class="dialog-footer">
          <t-button theme="primary" @click="submitDataScope">确 定</t-button>
          <t-button theme="default" @click="cancelDataScope">取 消</t-button>
        </div>
      </template>
    </t-dialog>
  </div>
</template>

<script setup name="Role">
import {
  addRole,
  changeRoleStatus,
  dataScope,
  delRole,
  getRole,
  listRole,
  updateRole,
  deptTreeSelect,
} from "@/api/system/role";
import {
  roleMenuTreeselect,
  treeselect as menuTreeselect,
} from "@/api/system/menu";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);
const roleRef = ref(null);
const menuExpandedKeys = ref([]);
const deptExpandedKeys = ref([]);

/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: "1", label: "全部数据权限" },
  { value: "2", label: "自定数据权限" },
  { value: "3", label: "本部门数据权限" },
  { value: "4", label: "本部门及以下数据权限" },
  { value: "5", label: "仅本人数据权限" },
]);

const columns = ref([
  {
    colKey: "row-select",
    type: "multiple",
    width: 50,
  },
  { colKey: "roleId", title: "角色编号", width: "120" },
  {
    colKey: "roleName",
    title: "角色名称",
    width: "150",
    ellipsis: true,
  },
  {
    colKey: "roleKey",
    title: "权限字符",
    width: "150",
    ellipsis: true,
  },
  { colKey: "roleSort", title: "显示顺序", width: "100" },
  { colKey: "status", title: "状态" },
  { colKey: "createTime", title: "创建时间" },
  { colKey: "action", title: "操作" },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roleName: undefined,
    roleKey: undefined,
    status: undefined,
  },
  rules: {
    roleName: [
      { required: true, message: "角色名称不能为空", trigger: "blur" },
    ],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    roleSort: [
      { required: true, message: "角色顺序不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 */
function getList() {
  loading.value = true;
  listRole(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      roleList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.roleId || ids.value;
  proxy.$modal
    .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
    .then(function () {
      return delRole(roleIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/role/export",
    {
      ...queryParams.value,
    },
    `role_${new Date().getTime()}.xlsx`
  );
}
/** 多选框选中数据 */
function handleSelectionChange(selectedRowKeys, { selectedRowData }) {
  ids.value = selectedRowKeys;
  single.value = selectedRowKeys.length != 1;
  multiple.value = !selectedRowKeys.length;
}
/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
    .then(function () {
      return changeRoleStatus(row.roleId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}
/** 分配用户 */
function handleAuthUser(row) {
  router.push("/system/role-auth/user/" + row.roleId);
}
/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then((response) => {
    menuOptions.value = response.data;
  });
}
/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  const nodes = deptRef.value.getItems();
  // 目前被选中的部门节点
  let checkedKeys = nodes
    .filter((item) => item.checked)
    .map((item) => item.value);
  // 半选中的部门节点
  let halfCheckedKeys = nodes
    .filter((item) => item.halfChecked)
    .map((item) => item.value);
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}
/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    form.value.menuIds = [];
  }
  menuExpand.value = false;
  menuNodeAll.value = false;
  deptExpand.value = true;
  deptNodeAll.value = false;
  form.value = {
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: "0",
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: undefined,
  };
  proxy.resetForm("roleRef");
}
/** 添加角色 */
function handleAdd() {
  reset();
  getMenuTreeselect();
  open.value = true;
  title.value = "添加角色";
}
/** 修改角色 */
function handleUpdate(row) {
  reset();
  const roleId = row.roleId || ids.value;
  const roleMenu = getRoleMenuTreeselect(roleId);
  getRole(roleId).then((response) => {
    form.value = response.data;
    form.value.roleSort = Number(form.value.roleSort);
    open.value = true;
    roleMenu.then((res) => {
      let checkedKeys = res.checkedKeys;
      checkedKeys.forEach((value) => {
        menuRef.value.setItem(value, { checked: true });
      });
    });
    title.value = "修改角色";
  });
}
/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId) {
  return roleMenuTreeselect(roleId).then((response) => {
    menuOptions.value = response.menus;
    return response;
  });
}
/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) {
  return deptTreeSelect(roleId).then((response) => {
    deptOptions.value = response.depts;
    return response;
  });
}
/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  if (type == "menu") {
    let treeList = menuOptions.value;
    menuExpandedKeys.value = value ? treeList.map((m) => m.id) : [];
  } else if (type == "dept") {
    let treeList = deptOptions.value;
    deptExpandedKeys.value = value ? treeList.map((m) => m.id) : [];
  }
}
/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  if (type == "menu") {
    const nodes = menuRef.value.getItems();
    for (let i = 0; i < nodes.length; i++) {
      menuRef.value.setItem(nodes[i].value, { checked: value });
    }
  } else if (type == "dept") {
    const nodes = deptRef.value.getItems();
    for (let i = 0; i < nodes.length; i++) {
      deptRef.value.setItem(nodes[i].value, { checked: value });
    }
  }
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  if (type == "menu") {
    form.value.menuCheckStrictly = value ? true : false;
  } else if (type == "dept") {
    form.value.deptCheckStrictly = value ? true : false;
  }
}
/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  const nodes = menuRef.value.getItems();
  // 目前被选中的菜单节点
  let checkedKeys = nodes
    .filter((item) => item.checked)
    .map((item) => item.value);
  // 半选中的菜单节点
  let halfCheckedKeys = nodes
    .filter((item) => item.indeterminate)
    .map((item) => item.value);
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}
/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["roleRef"].validate().then((valid) => {
    if (valid === true) {
      if (form.value.roleId != undefined) {
        form.value.menuIds = getMenuAllCheckedKeys();
        updateRole(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.menuIds = getMenuAllCheckedKeys();
        addRole(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 选择角色权限范围触发 */
function dataScopeSelectChange(value) {
  if (value !== "2") {
    deptRef.value.setCheckedKeys([]);
  }
}
/** 分配数据权限操作 */
function handleDataScope(row) {
  reset();
  const deptTreeSelect = getDeptTree(row.roleId);
  getRole(row.roleId).then((response) => {
    form.value = response.data;
    openDataScope.value = true;
    nextTick(() => {
      deptTreeSelect.then((res) => {
        nextTick(() => {
          if (deptRef.value) {
            res.checkedKeys.forEach((value) => {
              deptRef.value.setItem(value, { checked: true });
            });
          }
        });
      });
    });
    title.value = "分配数据权限";
  });
}
/** 提交按钮（数据权限） */
const submitDataScope = () => {
  if (form.value.roleId != undefined) {
    form.value.deptIds = getDeptAllCheckedKeys();
    dataScope(form.value).then((response) => {
      proxy.$modal.msgSuccess("修改成功");
      openDataScope.value = false;
      getList();
    });
  }
};
/** 取消按钮（数据权限）*/
function cancelDataScope() {
  openDataScope.value = false;
  reset();
}

getList();
</script>
